package com.chinaway.dsp.action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.json.JSONObject;

import com.chinaway.dsp.util.ApiUtil;

public class CallDspInterfaceAction {
	private String apiUrl ="http://test.dsp.chinawayltd.com/router/rest";
	private String appKey = "1088";
	private String appSecret = "httx";
	private String format = "json";
	private Shell shell=null;
	private BackAction ba;
	
	public CallDspInterfaceAction(String url,Shell s,BackAction b){
		this.shell=s;
		this.apiUrl=url;
		this.ba=b;
	}
	
	public String getHistory(String imei,String starttime) {
		String rs = getResult("huoyunren.gps.history", false, "imei", imei,"from",starttime,"page_size",1);
		JSONObject jsonobj = new JSONObject(rs);
		jsonobj=jsonobj.getJSONObject("data");
		String result=jsonobj.getString("result");
		return result;
	}
	
	public String getCurrent(String imei,String starttime) {
		Double lng=null;
		Double lat=null;
		Long gpstime_rep=null;
		
		String rs = getResult("huoyunren.gps.current", false, "imei", imei);
		System.out.println(rs);
		JSONObject jsonobj = new JSONObject(rs);
		try{
			jsonobj=jsonobj.getJSONObject("data");
			jsonobj=jsonobj.getJSONObject("location");
			gpstime_rep=jsonobj.getLong("gpstime");
			gpstime_rep=gpstime_rep/1000;
			lng=jsonobj.getDouble("lng");
			lat=jsonobj.getDouble("lat");
			
		}catch(org.json.JSONException e){
			MessageBox msgBox = new MessageBox( shell, SWT.YES | SWT.NO| SWT.ICON_QUESTION );
		    msgBox.setText( "调用失败!" );
		    msgBox.setMessage( "Current接口返回值异常,地图跟踪功能不可用\n点击   '是' 退出本程序,点击  '否' 程序还将继续发送数据\n如果该设备已绑定车辆,则可通过G7S轨迹回放功能查看本次轨迹" );
		    int message = msgBox.open();
		    if(64==message){
		    	System.exit(1);
		    }
		    if(128==message){
		    	ba.setCallDspInterface(false);
		    }
		    
		}
		return lng+","+lat+","+gpstime_rep;
	}
	
	private String getResult(String method, boolean sysout, Object...params) {
		final Map map = new HashMap();
		for (int i = 0; i < params.length; i += 2) {
			map.put(params[i], params[i+1]);
		}
		
		long start = System.currentTimeMillis();
		
		String result = getResult(method, sysout, map);
		
		if (sysout)
			System.out.println(method + "(" + (System.currentTimeMillis() - start) + "): " + result);
		return result;
	}
	
	private String getResult(String method, boolean sysout, Map<String, Object> map) {
		map.put("app_key", appKey);
		map.put("method", method);
		map.put("format", format);
		
		// 时间戳
		map.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		// 生成签名
		String sign = ApiUtil.sign(map, appSecret);
		// 组装协议参数sign
		map.put("sign", sign);
		
		String result = ApiUtil.createRequestParam(map);
		if (sysout)
			System.out.println(method + " param: " + result);
		result = ApiUtil.getResult(apiUrl, result);
		return result;
	}
}
